package com.tierstall.server;



import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;



import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.tierstall.client.service.SessionService;
import com.tierstall.server.model.User;
import com.tierstall.shared.Logger;
import com.tierstall.shared.SessionInvalidException;
import com.tierstall.shared.UserDTO;

@SuppressWarnings("serial")
public class SessionServiceImpl extends RemoteServiceServlet implements SessionService {
	ServiceHelper helper;
	
	public SessionServiceImpl(){
		helper = ServiceHelper.getInstance();
	}

	@Override
	public String loginRequest(String username,
			String password) {
		HttpSession session = getSession();
		User user = helper.getUserByUsername(username);
		if (user != null) {
			if (user.getPassword().equals(password)) {
				session.setAttribute("user", user);
				return session.getId();
			} else {
				Logger.SERVER_WARN("Server: Wrong password");
				return "wrong password";
			}
		} else
			return "not existing";
	}

	@Override
	public boolean checkSession(String sessionId)
			throws SessionInvalidException {
			return helper.checkSession(getSession(), sessionId);
	}

	@Override
	public UserDTO getLoggedInUser(String sessionId)
			throws SessionInvalidException {
		Logger.SERVER_INFO("getLoggedInUser for sessionID: " + sessionId);
		if (checkSession(sessionId)) {
			Logger.SERVER_INFO("Session containing User: " +((User) getSession().getAttribute("user")).getUsername());
			return helper.createUserDTO((User) getSession().getAttribute("user"));
		}
		return null;
	}
	
	private HttpSession getSession() {
			HttpServletRequest request = this.getThreadLocalRequest();
			return request.getSession();

	}

}
